<?php
/**
 * Created by PhpStorm OF yuyi.
 * User: YUYI
 * Date: 2018/5/18 0018
 * Time: 上午 10:20
 * Administrator
 */

namespace app\index\controller;


use app\common\controller\Base;
use app\common\model\Articles;
use app\common\model\Comments;
use app\common\service\UserService;
use think\Db;

class Comment extends Base
{
    public function index()
    {

    }

    public function add($id)
    {
        if (!($this->request->isAjax() || $this->request->isPost())){
            $this->error('非法访问');
        }
        $article = Articles::get($id);
        if (!$article){
            $this->error('无此文章');
        }
        Db::startTrans();
        $article->setInc('countComments');
        $user = UserService::getCurrentUserInfo();
        $r = Comments::create(['userId'=>$user['userId'],'articleId'=>$id,'content'=>input('content')]);
        if ($r){
            Db::commit();
            $this->success('评论成功！');
        }else{
            Db::rollback();
            $this->error('评论失败！');
        }
    }

    public function article($id=0)
    {
        $comments = Comments::all(['articleId'=>$id],['User','Article']);
        $this->assign('comments',$comments);
        return $this->fetch();
    }
}